import { Provide, Inject } from '@midwayjs/core';
import { RecordDao } from '../dao/recordDao';
import { Context } from '@midwayjs/koa';
import { GetFileExtension } from './originelFileName.service';
import { uuidv7 } from 'uuidv7';
import { join } from 'path';
import { OSSService } from '@midwayjs/oss';

@Provide()
export class RecordService {
  @Inject()
  ctx: Context;
  @Inject()
  recordDao: RecordDao;
  @Inject()
  getFileExtension: GetFileExtension;
  @Inject()
  ossService: OSSService;
  //查询记录是否存在
  async getRecordById(id: string) {
    return await this.recordDao.getRecordById(id);
  }
  //创建记录
  async createRecord(patientId: string) {
    return await this.recordDao.createRecord(patientId);
  }
  //获取记录
  async getRecordHistory(patientId: string) {
    return await this.recordDao.getRecordHistory(patientId);
  }
  //获取记录详情
  async getRecordDetails(id: string) {
    return await this.recordDao.getRecordDetails(id);
  }
  //删除记录
  async deleteRecord(id: string) {
    return await this.recordDao.deleteRecord(id);
  }
  //查找历史记录
  async getBloodRecordHistory(patientId: string) {
    return await this.recordDao.getBloodRecordHistory(patientId);
  }
  //原始图片存储
  async saveOriginalImage(originalImageUrl: string) {
      const filename = uuidv7() + '.' + 'jpg';
      const targetPath = join('oss', filename).replace(/\\/g, '/'); // 强制转换为POSIX路径格式
      const result = await this.ossService.put(targetPath, originalImageUrl); // 这里传递文件的路径
      if (result) {
        originalImageUrl = result.url;
      } else {
        throw new Error('上传图片失败');
      }
      return originalImageUrl;
  }
   //图片存储
   async saveImageDetection(data: Array<any>) {
    const uploadPromises = data.map(async (item) => {
      const originalFilename = item.type;
      const filename = uuidv7() + originalFilename + '.' + 'jpg';
      // 修正路径分隔符问题
      const targetPath = join('oss', filename).replace(/\\/g, '/'); // 强制转换为POSIX路径格式
      
      const result = await this.ossService.put(targetPath, item.imgPath);
      if (result) {
        item.imgPath = result.url;
      } else {
        throw new Error('上传图片失败');
      }
      return item;
    });
    
    return await Promise.all(uploadPromises);
  }
  //保存记录
  async saveRecord(data: any) {
    return await this.recordDao.saveRecord(data);
  }
}
